package com.curso.android.trabajo.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.curso.android.trabajo.db.MisSitiosDB.Sitios;

public class MisSitiosProvider extends ContentProvider {

	public static final Uri CONTENT_URI = Uri
			.parse("content://com.android.mis.sitios");
	// Diferentes accesos a los datos
	private static final int MISSITIOS = 1; // Acceso a todos los datos
	private static final int MISSITIOS_ID = 2; // Acceso a un id concreto
	private static final UriMatcher uriMatcher;

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI("com.android.mis.sitios", "sitios", MISSITIOS);
		uriMatcher.addURI("com.android.mis.sitios", "sitios/#", MISSITIOS_ID);
	}

	private SQLiteDatabase sitiosDB;

	@Override
	public int delete(Uri uri, String where, String[] whereargs) {
		int count = 0;

		switch (uriMatcher.match(uri)) {

		case MISSITIOS:
			count = sitiosDB.delete(Sitios.TABLE_NAME, where, whereargs);
			break;

		case MISSITIOS_ID:
			String id = uri.getPathSegments().get(1);
			count = sitiosDB.delete(Sitios.TABLE_NAME,
					Sitios._ID
							+ " = "
							+ id
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereargs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (uriMatcher.match(uri)) {
		// para conjunto
		case MISSITIOS:
			return "vnd.android.cursor.dir/vnd.curso.mis.sitios";
			// para un solo
		case MISSITIOS_ID:
			return "vnd.android.cursor.item/vnd.curso.mis.sitios";
		default:
			throw new IllegalArgumentException("Unsupported	URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// Inserta un nuevo sitio
		long rowID = sitiosDB.insert(Sitios.TABLE_NAME, "", values);
		// si todo ha ido ok devolvemos su Uri
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Erro to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		Context context = getContext();
		MisSitiosSQLHelper dbHelper = new MisSitiosSQLHelper(context,
				MisSitiosDB.DB_NAME, null, MisSitiosDB.DB_VERSION);
		sitiosDB = dbHelper.getWritableDatabase();
		return (sitiosDB == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(Sitios.TABLE_NAME);
		// consulta a un id concreto tenemos que hacer el where
		if (uriMatcher.match(uri) == MISSITIOS_ID) {
			sqlBuilder.appendWhere(Sitios._ID + " = "
					+ uri.getLastPathSegment());
		}

		if (sortOrder == null || sortOrder == "") {
			sortOrder = Sitios.DEFAULT_SORT_ORDER;
		}

		Cursor c = sqlBuilder.query(sitiosDB, projection, selection,
				selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int count = 0;

		switch (uriMatcher.match(uri)) {

		case MISSITIOS:
			count = sitiosDB.update(Sitios.TABLE_NAME, values, selection,
					selectionArgs);
			break;
		case MISSITIOS_ID:
			count = sitiosDB.update(Sitios.TABLE_NAME, values,
					Sitios._ID
							+ " = "
							+ uri.getPathSegments().get(1)
							+ (!TextUtils.isEmpty(selection) ? " AND ("
									+ selection + ')' : ""), selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
}
